﻿using K3Cloud.WebApi.Core.IoC;
using K3Cloud.WebApi.Core.IoC.DataEntity;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

// 生成Java实体类
namespace FormEntityCreationForJava
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            K3Services.AddK3Sugar();
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("请输入表单ID（FormId）:如：BD_STOCK");
            string FormID = Console.ReadLine();
            Console.ForegroundColor = ConsoleColor.White;
            if (string.IsNullOrEmpty(FormID)) { FormID = "BD_STOCK"; }
            int LanguageId1 = 2052;
            int LanguageId2 = 1033;
            K3ApiResult<K3BusinessInfoResult> k3BusinessInfoResult = K3Scoped.Client.QueryBusinessInfoAsync(FormID).GetAwaiter().GetResult();
            string jsonStr = JsonConvert.SerializeObject(k3BusinessInfoResult);
            File.WriteAllText(FormID + ".json", jsonStr);
            K3BusinessNeedReturn needReturnData = k3BusinessInfoResult.Result.NeedReturnData;
            List<JavaPropertyInfo> pyList = [];
            StringBuilder sb = new();
            string FormName = string.Empty;
            K3LanguageTranslate kl = needReturnData.Name.Find(x => x.Lcid == LanguageId1);
            FormName = kl != null ? kl.Value : needReturnData.Name.Find(x => x.Lcid == LanguageId2).Value;
            _ = sb.Append("import java.util.Optional;\r\n");
            _ = sb.Append("import java.lang.Long;\r\n");
            _ = sb.Append("import java.lang.Integer;\r\n");
            _ = sb.Append("import java.util.Date;\r\n");
            _ = sb.Append("import java.math.BigDecimal;\r\n");
            _ = sb.Append("import java.lang.String;\r\n");
            _ = sb.Append("import java.lang.Boolean;\r\n");
            _ = sb.Append("import java.lang.Object;\r\n");
            _ = sb.Append("import java.util.List;\r\n");
            _ = sb.Append("import java.util.ArrayList;\r\n");

            _ = sb.Append("/**\r\n");
            _ = sb.Append(" * " + FormName + "\r\n");
            _ = sb.Append(" */\r\n");
            _ = sb.Append("public class " + needReturnData.Id + " {\r\n");
            string pkFieldName = needReturnData.PkFieldName;
            Type pkFieldType = needReturnData.PkFieldType;
            _ = sb.Append("\t/**\r\n");
            _ = sb.Append("\t * " + pkFieldName + "\r\n");
            _ = sb.Append("\t */\r\n");
            _ = sb.Append("\tprivate " + K3BusinessToCSharpTypeForJava.GetJavaType(pkFieldType) + " " + pkFieldName + ";\r\n");
            pyList.Add(new JavaPropertyInfo
            {
                Name = pkFieldName,
                Type = K3BusinessToCSharpTypeForJava.GetJavaType(pkFieldType),
                Comment = pkFieldName
            });
            List<K3Table> entrys = needReturnData.Entrys;
            // 遍历entrys
            foreach (K3Table entry in entrys)
            {
                // 获取entry的Name的LanguageId语言值
                string entryName = string.Empty;
                K3LanguageTranslate ekl = entry.Name.Find(x => x.Lcid == LanguageId1);
                entryName = ekl != null ? ekl.Value : entry.Name.Find(x => x.Lcid == LanguageId2).Value;
                // 注释为entry的Name的LanguageId语言值
                _ = sb.Append("\t//#region " + entryName + "\r\n");
                // 获取entry的Key属性值
                string entryKey = entry.Key;
                // 获取entry的EntryPkFieldName属性值
                string entryPkFieldName = entry.EntryPkFieldName;
                // 获取entry的PkFieldType属性值
                Type entryPkFieldType = entry.PkFieldType;

                // 获取entry的SeqFieldKey属性值
                string seqFieldKey = entry.SeqFieldKey;
                if (!string.IsNullOrEmpty(seqFieldKey))
                {
                    // 注释为entry的PkFieldName属性值
                    _ = sb.Append("\t/**\r\n");
                    _ = sb.Append("\t * " + entryName + "主键" + entryPkFieldName + "\r\n");
                    _ = sb.Append("\t */\r\n");
                    _ = sb.Append("\tprivate " + K3BusinessToCSharpTypeForJava.GetJavaType(entryPkFieldType) + " " + entryKey + "_" + entryPkFieldName + ";\r\n");
                    // 注释为entry的SeqFieldKey属性值
                    _ = sb.Append("\t/**\r\n");
                    _ = sb.Append("\t * " + entryName + "序列\r\n");
                    _ = sb.Append("\t */\r\n");
                    _ = sb.Append("\tprivate Long " + entryKey + "_" + seqFieldKey + ";\r\n");
                    pyList.Add(new JavaPropertyInfo
                    {
                        Name = entryKey + "_" + entryPkFieldName,
                        Type = K3BusinessToCSharpTypeForJava.GetJavaType(entryPkFieldType),
                        Comment = entryName + "主键" + entryPkFieldName
                    });
                    pyList.Add(new JavaPropertyInfo
                    {
                        Name = entryKey + "_" + seqFieldKey,
                        Type = "Long",
                        Comment = entryName + "序列"
                    });
                }
                // 获取entry的Fields属性值
                List<K3FieldResult> fields = entry.Fields;
                // 遍历fields
                foreach (K3FieldResult field in fields)
                {
                    // 获取field的Name的LanguageId语言值
                    string fieldName = string.Empty;
                    K3LanguageTranslate klv = field.Name.Find(x => x.Lcid == LanguageId1);
                    fieldName = klv != null ? klv.Value : field.Name.Find(x => x.Lcid == LanguageId2).Value;
                    // 注释为field的Name的LanguageId语言值
                    _ = sb.Append("\t/**\r\n");
                    _ = sb.Append("\t * " + fieldName + "\r\n");
                    _ = sb.Append("\t */\r\n");
                    // 获取field的key属性值
                    string key = field.Key;
                    // 获取field的ElementType属性值
                    //var elementType = field.ElementType;
                    // 获取field的FieldType属性值
                    SqlStorageType fieldType = field.FieldType;
                    string fieldTypeString = K3BusinessToCSharpTypeForJava.GetJavaType(fieldType);
                    // 获取field的MustInput属性值
                    //var mustInput = field.MustInput;
                    //string mustInputStr = mustInput == 1 ? fieldTypeString : "Optional<" + fieldTypeString + ">";

                    _ = sb.Append("\tprivate " + fieldTypeString + " " + key + ";\r\n");
                    pyList.Add(new JavaPropertyInfo
                    {
                        Name = key,
                        Type = fieldTypeString,
                        Comment = fieldName
                    });
                    // 获取field的LookUpObjectFormId属性值
                    string lookUpObjectFormId = field.LookUpObjectFormId;
                    if (!string.IsNullOrEmpty(lookUpObjectFormId))
                    {
                        K3ApiResult<K3BusinessInfoResult> subBusinessInfo = K3Scoped.Client.GetBusinessInfoAsync(lookUpObjectFormId).GetAwaiter().GetResult();
                        List<K3FieldResult> subFields = subBusinessInfo.Result.NeedReturnData.Entrys
                            .Where(t => t.Fields.Any(x => x.Key is "FNumber" or "FName" or "FShortName" or "FDataValue"))
                            .Select(t => t.Fields).FirstOrDefault();
                        if (subFields == null) { continue; }
                        int subFieldsCount = 0;
                        for (int i = 0; i < subFields.Count; i++)
                        {
                            if (subFieldsCount >= 3) { break; }
                            if (subFields[i].Key.Equals("FNumber") || subFields[i].Key.Equals("FName") || subFields[i].Key.Equals("FShortName") || subFields[i].Key.Equals("FDataValue"))
                            {
                                string summaryTitle = string.Empty;
                                K3LanguageTranslate slv = subFields[i].Name.Find(t => t.Lcid == LanguageId1);
                                summaryTitle = slv != null ? slv.Value : subFields[i].Name.Find(x => x.Lcid == LanguageId2).Value;
                                _ = sb.Append("\t/**\r\n");
                                _ = sb.Append("\t * " + fieldName + summaryTitle + "\r\n");
                                _ = sb.Append("\t */\r\n");
                                _ = sb.Append("\tprivate String " + key + "_" + subFields[i].Key + ";\r\n");
                                pyList.Add(new JavaPropertyInfo
                                {
                                    Name = key + "_" + subFields[i].Key,
                                    Type = "String",
                                    Comment = fieldName + summaryTitle,
                                    SrcName = key + "." + subFields[i].Key
                                });
                                subFieldsCount++;
                            }
                        }
                    }
                }
                _ = sb.Append("\t//#endregion" + "\r\n");
            }
            for (int i = 0; i < pyList.Count; i++)
            {
                _ = sb.Append("\t/**\r\n");
                _ = sb.Append("\t * " + pyList[i].Comment + "\r\n");
                _ = sb.Append("\t */\r\n");
                _ = sb.Append("\tpublic void set" + pyList[i].Name + "(" + pyList[i].Type + " " + pyList[i].Name.ToLower() + ") {\r\n");
                _ = sb.Append("\t\t this." + pyList[i].Name + " = " + pyList[i].Name.ToLower() + ";\r\n");
                _ = sb.Append("\t}\r\n");

                _ = sb.Append("\t/**\r\n");
                _ = sb.Append("\t * " + pyList[i].Comment + "\r\n");
                _ = sb.Append("\t */\r\n");
                _ = sb.Append("\tpublic " + pyList[i].Type + " get" + pyList[i].Name + "() {\r\n");
                _ = sb.Append("\t\t return " + pyList[i].Name + ";\r\n");
                _ = sb.Append("\t}\r\n");
            }

            _ = sb.Append('}');
            _ = sb.Append("\r\n");
            _ = sb.Append("// K3CloudApi api = new K3CloudApi();\r\n");
            _ = sb.Append("// QueryParam data = new QueryParam();\r\n");
            _ = sb.Append("// data.setFormId(\"" + needReturnData.Id + "\");\r\n");
            _ = sb.Append("// data.setFieldKeys(\"" + string.Join(',', pyList.Select(t => string.IsNullOrEmpty(t.SrcName) ? t.Name : t.SrcName).ToArray()) + "\");\r\n");
            _ = sb.Append("// data.setStartRow(0);\r\n");
            _ = sb.Append("// data.setLimit(50);\r\n");
            _ = sb.Append("// List<" + needReturnData.Id + "> result = api.executeBillQuery(data, " + needReturnData.Id + ".class);\r\n");
            _ = sb.Append("// Gson gson = new Gson();\r\n");
            _ = sb.Append("// System.out.println(gson.toJson(result));\r\n");
            Console.WriteLine(sb.ToString());
            // 将生成的实体类写入到文件中
            File.WriteAllText("../../../DataEntity/" + needReturnData.Id + ".java", sb.ToString());
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("...按任意键结束...");
            _ = Console.ReadKey();
        }
    }
}
